
package com.dps.omc.action;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dps.omc.enumer.EnumGroupType;
import com.dps.omc.model.*;
import com.dps.omc.monitor.AgentMonitor;
import com.dps.omc.monitor.AgentState;
import com.dps.omc.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dps.common.domain.view.BizData4Page;
import com.dps.common.utils.IdGenerator;
import com.dps.common.utils.JsonResult;
import com.dps.common.utils.PageParam;
import com.dps.common.utils.Constants;

@Controller
public class AgentAction extends AbstractAdminController<IAgentService>{

    @Autowired
    private IAgentService agentService;
    @Autowired
    private IGroupService groupService;
    @Autowired
    private IGroupTypeService groupTypeService;
    @Autowired
    private IBizUnitService bizUnitService;
    @Autowired
    private IOsTypeService osTypeService;
    @Autowired
    private ISystemRankService systemRankService;
    @Autowired
    private IDbServerService dbServerService;
    @Autowired
    private IAgentNodeService agentNodeService;
    @Autowired
    private IServerService serverService;
    @Autowired
    private ITelnetServerService telnetServerService;
    @Autowired
    private AgentMonitor agentMonitor;
    
    @RequestMapping(value="/agent/list")
    public String list(Agent agent, ModelMap model, PageParam pageParam, HttpServletRequest request, HttpServletResponse response){

        //获取参数
    	Map<String, Object> conditions = getQueryMap(agent); 	
    	BizData4Page<Agent> pageCtx = doPage(model, conditions, pageParam);
    	model.addAttribute("agent", agent);
    	return "/module/agent/list";
    }

    @RequestMapping(value="/agent/tree")
    public String tree(Agent agent,ModelMap model,PageParam pageParam,HttpServletRequest request,HttpServletResponse response){

        //获取参数
//        Map<String, Object> conditions = getQueryMap(agent);
//        BizData4Page<Agent> pageCtx = doPage(model, conditions, pageParam);
//        model.addAttribute("agent", agent);

        List<BizUnit> bizUnits =  bizUnitService.findAll();
        List<Agent> agents = agentService.findAll();
        Map agentMap = this.getAgentMap(bizUnits,agents);
        model.addAttribute("bizUnits", bizUnits);
        model.addAttribute("agentMap", agentMap);
        return "/module/agent/tree";
    }

    @RequestMapping(value="/agent/node")
    public String node(String agentId,ModelMap model,HttpServletRequest request,HttpServletResponse response){


        model.addAttribute("agentId" ,agentId);
        return "/module/agent/node";
    }

    @RequestMapping(value="/agent/listunbind")
    public String listUnbind(String groupType,ModelMap model,HttpServletRequest request,HttpServletResponse response){

        List rows = null;

//        List<DbServer> dbServers = dbServerService.findUnbind();
        if(EnumGroupType.valueOf(groupType).equals(EnumGroupType.SERVER))
        {
            rows = serverService.findUnbind();
        }
        else if(EnumGroupType.valueOf(groupType).equals(EnumGroupType.TELNET))
        {
            rows = telnetServerService.findUnbind();
        }
        else
        {
            rows = dbServerService.findUnbind();
        }

        model.addAttribute("rows" ,rows);
        return "/module/agent/list_unbind";
    }

    @RequestMapping(value="/agent/listbind")
    public String listBind(String groupType,String agentId,ModelMap model,HttpServletRequest request,HttpServletResponse response){

//        List<DbServer> dbServers = dbServerService.findList("agentId",agentId);
        List rows = null;
        if(EnumGroupType.valueOf(groupType).equals(EnumGroupType.SERVER))
        {
            rows = serverService.findList("agentId",agentId);
        }
        else if(EnumGroupType.valueOf(groupType).equals(EnumGroupType.TELNET))
        {
            rows = telnetServerService.findList("agentId",agentId);
        }
        else
        {
            rows = dbServerService.findList("agentId",agentId);
        }
        model.addAttribute("rows" ,rows);
        return "/module/agent/list_bind";
    }

    @RequestMapping(value="/agent/node/bind")
    @ResponseBody
    public String bindNode(String groupType,String agentId,String unbindIds,ModelMap model,HttpServletRequest request,HttpServletResponse response){

        String[] ids = unbindIds.split(",");
        Agent agent = agentService.fetch(agentId);
        if(EnumGroupType.valueOf(groupType).equals(EnumGroupType.SERVER))
        {
            for(String id:ids)
            {
                Server server = serverService.fetch(id);
                server.setAgentId(agentId);
                serverService.update(server);
                agentNodeService.createByServer(agent, server);
            }
        }
        else if(EnumGroupType.valueOf(groupType).equals(EnumGroupType.TELNET))
        {
            for(String id:ids)
            {
                TelnetServer telnetServer = telnetServerService.fetch(id);
                telnetServer.setAgentId(agentId);
                telnetServerService.update(telnetServer);
                agentNodeService.createByTelnetServer(agent, telnetServer);
            }
        }
        else
        {
            for(String id:ids)
            {
                DbServer dbServer = dbServerService.fetch(id);
                dbServer.setAgentId(agentId);
                dbServerService.update(dbServer);
                agentNodeService.createByDbServer(agent,dbServer);
            }
        }

        return JsonResult.operateSuccess(Constants.MAIN_TAB).toString();
    }

    @RequestMapping(value="/agent/node/unbind")
    @ResponseBody
    public String unbindNode(String groupType,String bindIds,ModelMap model,HttpServletRequest request,HttpServletResponse response){

        String[] ids = bindIds.split(",");

        if(EnumGroupType.valueOf(groupType).equals(EnumGroupType.SERVER))
        {
            for(String id:ids)
            {
                serverService.unbind(id);
                agentNodeService.deleteByProperty("nodeId", id);
            }
        }
        else if(EnumGroupType.valueOf(groupType).equals(EnumGroupType.TELNET))
        {
            for(String id:ids)
            {
                telnetServerService.unbind(id);
                agentNodeService.deleteByProperty("nodeId", id);
            }
        }
        else
        {
            for(String id:ids)
            {
                dbServerService.unbind(id);
                agentNodeService.deleteByProperty("nodeId", id);
            }
        }

        return JsonResult.operateSuccess(Constants.MAIN_TAB).toString();
    }

    private Map<String,List<Agent>> getAgentMap(List<BizUnit> bizUnits,List<Agent> agents)
    {
        Map map = new HashMap<>();
        for(BizUnit bizUnit:bizUnits)
        {
            List<Agent> list = new ArrayList<>();
            map.put(bizUnit.getId(),list);
        }

        for(Agent agent:agents)
        {
            String bizUnitId = agent.getBizUnitId();
            if(map.get(bizUnitId)!=null)
            {
                List<Agent> agentList = (List<Agent>) map.get(bizUnitId);
                agentList.add(agent);
            }
        }

        return map;
    }


    @RequestMapping(value="/agent/add")
    public String add(ModelMap model,HttpServletRequest request,HttpServletResponse response){

//        List<Group> groups = groupService.findAll();
        List<BizUnit> units = bizUnitService.findAll();
//        List<GroupType> groupTypes = groupTypeService.findAll();
        EnumGroupType[] groupTypes = EnumGroupType.values();
        List<OsType> osTypes = osTypeService.findAll();
        List<SystemRank> systemRanks = systemRankService.findAll();
//        model.addAttribute("gps", groups);
        model.addAttribute("osTypes", osTypes);
        model.addAttribute("sysRanks", systemRanks);
        model.addAttribute("groupTypes", groupTypes);
        model.addAttribute("units", units);
        model.addAttribute("agent", new Agent());
        return "module/agent/edit";
    }    
    
    @RequestMapping(value="/agent/edit")
    public String edit(String id,ModelMap model,HttpServletRequest request,HttpServletResponse response){

        Agent agent = agentService.fetch(id);
//        List<Group> groups = groupService.findAll();
        List<BizUnit> units = bizUnitService.findAll();
//        List<GroupType> groupTypes = groupTypeService.findAll();
        EnumGroupType[] groupTypes = EnumGroupType.values();
        List<OsType> osTypes = osTypeService.findAll();
        List<SystemRank> systemRanks = systemRankService.findAll();
//        model.addAttribute("gps", groups);
        model.addAttribute("osTypes", osTypes);
        model.addAttribute("sysRanks", systemRanks);
        model.addAttribute("groupTypes", groupTypes);
        model.addAttribute("units", units);
        model.addAttribute("agent", agent);
        return "module/agent/edit";
    }    
    
    @RequestMapping(value="/agent/save")
    @ResponseBody
    public String save(HttpServletRequest request,Agent agent){
		boolean isAddNew = StringUtils.isBlank(agent.getId())?true:false;

        //通过该方法getCurrentUser获取已认证用户的一些属性，用user来接收
        User user=getCurrentUser();
		if(isAddNew)
		{
			agent.setId(IdGenerator.createNewId());
            agent.setEnable(false);
            agent.setCreaterId(user.getId());
            agent.setCreaterName(user.getRealName());
			agentService.add(agent);
		}
		else
		{
            agent.setUpdaterId(user.getId());
            agent.setUpdaterName(user.getRealName());
			agentService.update(agent);
		}
        return JsonResult.saveSuccessClose(Constants.MAIN_TAB).toString();
    }    
    
    @RequestMapping(value="/agent/delete")
    @ResponseBody
    public String delete(String ids,HttpServletRequest request){
    	
    	agentService.deleteByIds(ids);
    	return JsonResult.DELETE_SUCCESS.toString();
    }

    @RequestMapping(value="/agent/monitor")
    public String monitor(String id,ModelMap model,HttpServletRequest request,HttpServletResponse response){

        List<AgentState> agentStates = new ArrayList<>();
        Map<String,AgentState> map = agentMonitor.getMap();

        Set<String> set = map.keySet();
        for(String key:set)
        {
            AgentState agentState = map.get(key);
            agentStates.add(agentState);
        }
        model.addAttribute("agentStates", agentStates);
        return "module/agent/monitor";
    }

    @RequestMapping(value="/agent/detail")
    public String detail(String agentId,ModelMap model,HttpServletRequest request,HttpServletResponse response){

        Agent agent = agentService.fetch(agentId);
        model.addAttribute("agent",agent);
        return "/module/agent/detail";
    }


    protected Map getQueryMap(Agent agent)
    {
        Map<String, Object> conditions = new HashMap();

        conditions.put("ip", agent.getIp());
        conditions.put("name", agent.getName());
        conditions.put("connectKey", agent.getConnectKey());
        conditions.put("version", agent.getVersion());
        conditions.put("groupType", agent.getGroupType());
        conditions.put("bizUnitId", agent.getBizUnitId());
        conditions.put("bizUnitName", agent.getBizUnitName());
        conditions.put("enable", agent.getEnable());
        conditions.put("createrId", agent.getCreaterId());
        conditions.put("updateDate", agent.getUpdateDate());
        conditions.put("updaterName", agent.getUpdaterName());
        conditions.put("createrName", agent.getCreaterName());
        conditions.put("updaterId", agent.getUpdaterId());
        conditions.put("createDate", agent.getCreateDate());
        conditions.put("opSystem", agent.getOpSystem());
        conditions.put("sysRank", agent.getSysRank());
        conditions.put("userName", agent.getUserName());
        conditions.put("password", agent.getPassword());
        return conditions;
    }

    @Override
    protected IAgentService getMainService() {
        return agentService;
    }

    @Override
    protected String getMainObjName() {
        return "agent";
    }

    @Override
    protected String getViewTitle() {
        return "agent";
    }
}
